<template>
	<basic-container class="basic-box">
		<el-container>
			<el-aside width="200px">
				<div class="list-tree-box">
					<avue-tree
						class="filter-tree"
						:option="treeOption"
						v-model="treeForm"
						:data="treeData"
						@node-click="nodeClick"
						@update="updateT"
						@save="rowSaveT"
						@del="delnodeT"
					>
						<template slot-scope="scope" slot="menuBtn">
							<div style="padding: 0 10px;">
								<el-dropdown-item @click.native="addTree">新增</el-dropdown-item>
								<el-dropdown-item @click.native="editTree(scope.data)">修改</el-dropdown-item>
								<el-dropdown-item @click.native="delTree(scope.data)">删除</el-dropdown-item>
							</div>
						</template>
					</avue-tree>
				</div>
			</el-aside>
			<el-main>
				<avue-crud
					:data="data"
					:option="option"
					v-model="form"
					:page="page"
					@row-del="rowDel"
					@selection-change="selectionChange"
					@current-change="currentChange"
					@size-change="sizeChange"
				>
					<template slot-scope slot="menuLeft">
						<el-button type="primary" size="small" plain class="addBtn" :style="{ display: addClassBtn }" @click="addPageInfoClass">+新增分类</el-button>

						<el-button type="primary" size="small" plain class="addBtn" @click="addArticle">+新增</el-button>

						<el-button type="primary" size="small" plain class="addBtn" @click="allDelete">批量删除</el-button>
					</template>
					<template slot-scope="{ row }" slot="picUrl">
						<img :src="row.picUrl" style="width:50px;height:50px;" />
					</template>
					<template slot-scope="{ row, type, size }" slot="menu">
						<el-button :type="type" :size="size" icon="el-icon-view" @click="getEdit(row, 'check')">查看</el-button>
						<el-button :type="type" :size="size" icon="el-icon-edit" @click="getEdit(row, 'edit')">编辑</el-button>
						<el-button :type="type" :size="size" icon="el-icon-edit" @click="toDesign(row)">设计</el-button>
					</template>
				</avue-crud>

				<!--新增分类，用于"+新增"的点击事件-->
				<el-dialog title="新增分类" :visible.sync="addClassDialogTableVisible" size="70%" :close-on-click-modal="false" :show-close="false">
					<el-form :model="addClassForm" ref="addClassForm" :rules="addClassFormRule" label-width="110px" class="demo-ruleForm">
						<el-form-item label="页面分类名称" prop="title">
							<el-input v-model="addClassForm.title" placeholder="请输入页面分类名称" size="mini"></el-input>
						</el-form-item>
					</el-form>
					<span slot="footer" class="dialog-footer">
						<el-button type="primary" size="mini" @click="commitAddClassCheck('addClassForm')" :loading="loadAddClassBtn">确 定</el-button>
						<el-button size="mini" @click="cancelAddClass('addClassForm')">取 消</el-button>
					</span>
				</el-dialog>

				<!--用于tree的自定义新增分类-->
				<el-dialog :title="addOrUpdateClass" :visible.sync="treeDialogTableVisible" @close="cancelAddTree" width="70%">
					<avue-form ref="treeForms" v-model="treeForms" :loading="loadingNewTree" :option="optionTree" @submit="submitTree">
						<template slot="menuForm">
							<el-button size="mini" @click="cancelAddTree">取 消</el-button>
						</template>
					</avue-form>
				</el-dialog>

				<!--新增-->
				<el-dialog :title="titleBan" :visible.sync="addDialogTableVisible" @before-close="cancelAdd" size="70%">
					<!--          :close-on-click-modal="false"-->
					<!--          :show-close="false"-->
					<avue-form ref="addForms" v-model="addForm" :loading="loadingAddTree" :option="optionAddTree" @submit="commitAddCheck">
						<template slot-scope="scope" slot="picUrl">
							<div class="upload">
								<el-input
									style="margin-right: 0.2rem;"
									@focus="openSelFile"
									v-model="addForm.picUrl"
									:clearable="true"
									placeholder="请选择预览图"
									:readonly="true"
								/>
								<el-image
									v-if="addForm.picUrl"
									@click="openSelFile"
									fit="contain"
									:src="addForm.picUrl"
									style="margin-right: 0.2rem;width: 50px; height: 50px"
								></el-image>
<!--								<el-button size="mini" type="primary" icon="el-icon-search" @click="openSelFile">预览</el-button>-->
							</div>
						</template>
						<template slot="menuForm">
							<el-button size="mini" @click="cancelAdd">取 消</el-button>
						</template>
					</avue-form>
				</el-dialog>
			</el-main>
			<selFile ref="selFile" @callback="selFileCallBack" albumCode="pic_root" dialogTitle="选择图片" selectType="radio" selMaxWidth="300px" selMaxHeight="300px"></selFile>
		</el-container>
	</basic-container>
</template>

<script>
import selFile from '@/components/file/selFile';
import uploadPic from '@/components/file/uploadPic';
import { testGoodsName } from '@/util/util';
import { pageTitle } from '@/util/rej';
import { getList, remove, update, add, getDetail, removeAll } from '@/api/cms/pageInfo';

import { getTree, updateClass, addClass, removeClass, getListsDicData } from '@/api/cms/pageClass';
import { mapGetters } from 'vuex';

var Dict = JSON.parse(localStorage.getItem('mall-dictionary')).content;
export default {
	data() {
		return {
			titleBan: '',
			pageClassOption: {},
			form: {},
			treeForm: {},
			query: {},
			loading: true,
			rolesTree: [],
			rolesKeys: [],
			srcList: [],
			idList: [],
			box: false,
			loadingNewTree: false,
			loadingAddTree: false,
			addDialogTableVisible: false,
			editDialogTableVisible: false,
			addClassDialogTableVisible: false,
			treeDialogTableVisible: false,
			addClassBtn: 'none', //隐藏
			addOrUpdateClass: '新增分类',
			albumCode: 'pic_root',
			loadAddBtn: false,
			loadEditBtn: false,
			loadAddClassBtn: false,
			pageClassId: '',
			page: {
				pageSize: 10,
				currentPage: 1,
				total: 0
			},
			option: {
				size: 'mini',
				excelBtn: false,
				tip: false,
				border: true,
				index: false,
				selection: true,
				viewBtn: false,
				addBtn: false,
				editBtn: false,
				rowKey: 'id',
				height: 'auto',
				// calcHeight: 380,
				dialogType: 'drawer',
				menuWidth: 260,
				column: [
					{
						label: '页面名称',
						prop: 'title',
						fixed: true,
						rules: [
							{
								required: true,
								message: '请输入页面名称',
								trigger: 'blur'
							}
						]
					},
					{
						label: '页面状态',
						prop: 'pageStatus',
						dicData: Dict.PAGE_INFO_STATUS,
						rules: [
							{
								required: true,
								message: '请输入页面状态 0不使用 1正在使用',
								trigger: 'blur'
							}
						]
					},
					//  暂时先注释掉
					// {
					//   label: "用户",
					//   prop: "userName",
					//   fixed: true,
					//   rules: [{
					//     required: true,
					//     message: "请输入用户ID",
					//     trigger: "blur"
					//   }]
					// },
					// {
					//   label: "店铺",
					//   prop: "storeName",
					//   fixed: true,
					//   rules: [{
					//     required: true,
					//     message: "请输入店铺ID",
					//     trigger: "blur"
					//   }]
					// },
					// {
					//   label: "皮肤",
					//   prop: "skinName",
					//   fixed: true,
					//   rules: [{
					//     required: true,
					//     message: "请输入皮肤ID",
					//     trigger: "blur"
					//   }]
					// },
					{
						label: '修改时间',
						prop: 'updateTime',
						rules: [
							{
								required: true,
								message: '请输入修改时间',
								trigger: 'blur'
							}
						]
					},
					{
						label: '预览图',
						prop: 'picUrl',
						slot: true,
						rules: [
							{
								required: true,
								message: '请输入预览图',
								trigger: 'blur'
							}
						]
					}
				]
			},
			treeOption: {
				dialogWidth: '70%',
				nodeKey: 'id',
				size: 'small',
				addBtn: false,
				editBtn: false,
				filter: false,
				delBtn: false,
				rowKey: 'id',
				searchMenuSpan: 6,
				formOption: {
					labelWidth: 130,
					query: {},
					loading: true,
					addBtn: true,
					saveBtn: true,
					menuPostion: 'right',
					submitBtn: true,
					emptyBtn: true,
					submitSize: 'small',
					submitText: '保存',
					emptyText: '清空',
					emptySize: 'small',
					column: [
						{
							label: '父类',
							prop: 'parentId',
							fixed: true,
							search: true,
							type: 'select',
							dicUrl: '/cms/pageClass/listsDicData'
						}
					]
				},
				props: {
					labelText: '页面分类名称',
					value: 'value',
					label: 'label',
					children: 'children'
				}
			},
			optionAddTree: {
				size: 'mini',
				submitBtn: true,
				emptyBtn: false,
				submitText: '提交',
				submitSize: 'small',
				column: [
					{
						label: '页面分类名称',
						labelWidth: 150,
						prop: 'title',
						span: 24,
						disabled: false,
						rules: [
							{
								required: true,
								message: '页面分类名称',
								trigger: 'blur'
							},
							{
								validator: pageTitle,
								trigger: 'blur'
							}
						]
					},
					{
						label: '页面介绍',
						labelWidth: 150,
						prop: 'introduce',
						span: 24,
						disabled: false,
						rules: [
							{
								required: true,
								message: '请输入页面介绍',
								trigger: 'blur'
							},
							{
								validator: testGoodsName,
								trigger: 'blur'
							}
						]
					},
					{
						label: '页面状态',
						labelWidth: 150,
						prop: 'pageStatus',
						disabled: false,
						span: 24,
						type: 'select',
						dicData: Dict.PAGE_INFO_STATUS,
						rules: [
							{
								required: true,
								message: '请选择页面状态',
								trigger: 'change'
							}
						]
					},
					{
						label: '页面链接',
						labelWidth: 150,
						span: 24,
						disabled: false,
						prop: 'pageUrl'
					},
					{
						label: '预览图',
						labelWidth: 150,
						span: 24,
						disabled: false,
						prop: 'picUrl',
						formslot: true
					},
					{
						label: '页面分类',
						labelWidth: 150,
						span: 24,
						disabled: false,
						prop: 'pageClassId',
						type: 'select',
						dicData: [],
						rules: [
							{
								required: true,
								message: '请选择页面状态',
								trigger: 'change'
							}
						]
					}
				]
			},
			optionTree: {
				addBtn: false,
				size: 'mini',
				border: true,
				viewBtn: false,
				editBtn: false,
				delBtn: false,
				rowKey: 'id',
				height: 'auto',
				menuWidth: 150,
				align: 'center',
				submitBtn: true,
				emptyBtn: false,
				submitText: '提交',
				submitSize: 'small',
				column: [
					{
						label: '页面分类名称',
						labelWidth: '150',
						prop: 'title',
						fixed: true,
						rules: [
							{
								required: true,
								message: '页面分类名称',
								trigger: 'blur'
							},
							{
								validator: pageTitle,
								trigger: 'blur'
							}
						]
					},
					{
						label: '父类',
						prop: 'parentId',
						fixed: true,
						type: 'select',
						dicData: []
					}
				]
			},
			data: [],
			treeData: [],
			addForm: {},
			addClassForm: {},
			editForm: {},
			treeForms: {},
			addClassFormRule: {
				title: [
					{
						required: true,
						message: '页面名称不能为空'
					},
					{
						min: 2,
						max: 10,
						message: '长度在 2 到 10个字符'
					}
				]
			}
		};
	},
	computed: {
		...mapGetters(['permission', 'userInfo']),
		permissionList() {
			return {
				addBtn: this.vaildData(this.permission[''], false),
				viewBtn: this.vaildData(this.permission[''], false),
				delBtn: this.vaildData(this.permission[''], false),
				editBtn: this.vaildData(this.permission[''], false)
			};
		}
	},

	created() {
		this.getTreeList();
		this.loadClass(5)
		this.onLoad(this.page);
	},

	watch: {
		treeData() {
			if (this.treeData.length == 0) {
				//展示
				this.addClassBtn = '';
			} else {
				//不显示
				this.addClassBtn = 'none';
			}
		}
	},

	components: {
		selFile,
		uploadPic
	},

	methods: {
		openSelFile() {
			if (this.titleBan != '查看') {
				this.$refs.selFile.open();
			}
		},
		toDesign(row) {
			this.$router.push({
				path: `/page/editor?id=` + row.id
			});
		},
		rowDel(row) {
			this.$confirm('确定将选择数据删除?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					return remove(row.id);
				})
				.then(() => {
					if (this.data.length == 1) {
						this.page.currentPage -= 1;
					}
					this.onLoad(this.page);
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
				});
		},

		//监控多选点击事件
		selectionChange(row) {
			var idList = [];
			if (row.length > 0) {
				for (let item of row) {
					idList.push(item.id);
				}
				this.idList = idList;
			} else {
				this.idList = [];
			}
		},

		searchReset() {
			this.query = {};
			this.idList = [];
			this.onLoad(this.page);
		},
		searchChange(params) {
			this.query = params;
			this.onLoad(this.page, params);
		},
		currentChange(currentPage) {
			this.page.currentPage = currentPage;
			this.onLoad(this.page);
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
			this.onLoad(this.page);
		},

		refreshChange() {
			this.onLoad(this.page);
		},

		onLoad(
			page,
			params = {
				pageClassId: this.pageClassId,
				pageType: 2
			}
		) {
			this.loading = true;
			getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
				this.loading = false;
				const data = res.data;
				this.page.total = data.count;
				this.data = data.data;
			});
		},

		nodeClick(data) {
			this.pageClassId = data.value;
			this.page.currentPage = 1;
			this.onLoad(this.page);
		},

		updateT(data, node, done) {
			this.treeForm.title = this.treeForm.label;
			updateClass(this.treeForm).then(res => {
				if (res.data.success) {
					this.$message({
						type: 'success',
						message: '修改成功!'
					});
					this.getTreeList();
					location.reload();
					done();
				}
			});
		},

		rowSaveT(row, loading, done) {
			this.treeForm.title = this.treeForm.label;
			if (!this.treeForm.title) {
				done();
				this.getTreeList();
				return this.$message.error('请输入标题');
			}
			if (this.treeForm.title.length < 3 || this.treeForm.title.length > 20) {
				done();
				this.getTreeList();
				return this.$message.error('字数请保持在3~20个');
			}
			addClass(this.treeForm).then(res => {
				if (res.data.code == 200) {
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
					this.getTreeList();
					location.reload();
					done();
				} else {
					this.$message.error(res.data.message);
					done();
				}
			});
		},

		delnodeT(row, loading, done) {
			removeClass(row.value).then(res => {
				if (res.data.code == 200) {
					this.loading = false;
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
					this.getTreeList();
					location.reload();
					done();
				} else {
					this.$message.error(res.data.message);
				}
			});
		},

		delTree(row) {
			this.$confirm('是否确认删除该节点?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				return removeClass(row.value).then(res => {
					if (res.data.success) {
						this.loading = false;
						this.$message.success('操作成功!');
						this.getTreeList();
						// location.reload();
					} else {
						this.$message.error(res.data.message);
					}
				});
			});
		},

		getTreeList() {
			getTree().then(res => {
				for (let item of res.data.data) {
					item.id = item.value;
				}
				this.treeData = res.data.data;
			});
		},

		//全选删除
		allDelete() {
			removeAll(this.idList).then(
				res => {
					if (this.idList.length > 0) {
						if (res.data.success) {
							this.page.currentPage = 1;
							this.onLoad(this.page, this.params);
							this.idList = [];
							this.$message({
								type: 'success',
								message: '操作成功!'
							});
						} else {
							this.$message.error(res.data.message);
						}
					} else {
						this.$message({
							type: 'error',
							message: '至少选择一笔数据'
						});
					}
				},
				error => {
					console.log(error);
				}
			);
		},

		//新增分类
		addPageInfoClass() {
			this.addClassDialogTableVisible = true;
		},

		addArticle() {
			this.titleBan = '新增';
			this.addForm.pageClassId = this.pageClassId; //新增的时候，回显左侧选中的分类
			this.addDialogTableVisible = true;
		},
		//编辑
		getEdit(row, type) {
			this.loadClass(5)
			if (type == 'check') {
				this.optionAddTree.submitBtn = false;
				this.optionAddTree.column[0].disabled = true;
				this.optionAddTree.column[1].disabled = true;
				this.optionAddTree.column[2].disabled = true;
				this.optionAddTree.column[3].disabled = true;
				this.optionAddTree.column[4].disabled = true;
				this.optionAddTree.column[5].disabled = true;
				this.titleBan = '查看';
			} else if (type == 'edit') {
				this.optionAddTree.submitBtn = true;
				this.optionAddTree.column[0].disabled = false;
				this.optionAddTree.column[1].disabled = false;
				this.optionAddTree.column[2].disabled = false;
				this.optionAddTree.column[3].disabled = false;
				this.optionAddTree.column[4].disabled = false;
				this.optionAddTree.column[5].disabled = false;
				this.titleBan = '编辑';
			}
			getDetail(row.id).then(res => {
				if (res.data.code == 200) {
					this.addForm = res.data.data;
					this.addDialogTableVisible = true;
				} else {
					this.$message({
						message: res.data.message,
						type: 'error'
					});
					return;
				}
			});
		},

		getAddContent(val) {
			this.objAdd.content = val;
		},
		//新增提交
		commitAddCheck(loading, done) {
			this.loadingAddTree = true;
			if (this.addForm.id) {
				update(this.addForm).then(res => {
					if (res.data.code == 200) {
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
						this.loadingAddTree = false;
						this.cancelAdd();
						this.onLoad(this.page);
					} else {
						this.loadingAddTree = false;
						this.$message({
							type: 'error',
							message: res.data.message
						});
					}
					done();
				});
			} else {
				add(this.addForm).then(res => {
					if (res.data.code == 200) {
						this.$message({
							type: 'success',
							message: '操作成功!'
						});
						this.loadingAddTree = false;
						this.cancelAdd();
						this.onLoad(this.page);
					} else {
						this.loadingAddTree = false;
						this.$message({
							type: 'error',
							message: res.data.message
						});
					}
					done();
				});
			}
			this.optionAddTree.column[0].disabled = false;
			this.optionAddTree.column[1].disabled = false;
			this.optionAddTree.column[2].disabled = false;
			this.optionAddTree.column[3].disabled = false;
			this.optionAddTree.column[4].disabled = false;
			this.optionAddTree.column[5].disabled = false;
		},

		//新增取消
		cancelAdd() {
			this.addDialogTableVisible = false;
			this.$nextTick(() => {
				this.$refs.addForms.resetForm();
				this.$refs.addForms.clearValidate();
			});
		},
		//新增分类提交
		commitAddClassCheck(addClassForm) {
			this.$refs[addClassForm].validate(valid => {
				if (valid) {
					this.loadAddClassBtn = true;
					addClass(this.addClassForm).then(res => {
						if (res.data.code == 200) {
							this.$message({
								type: 'success',
								message: '操作成功!'
							});
							this.loadAddClassBtn = false;
							this.$refs.addClassForm.resetFields();
							this.addClassDialogTableVisible = false;
							this.getTreeList();
						} else {
							this.loadAddClassBtn = false;
							this.$message({
								type: 'error',
								message: res.data.message
							});
						}
					});
				} else {
					this.loadAddClassBtn = false;
				}
			});
		},

		//新增分类取消
		cancelAddClass() {
			this.$refs.addClassForm.resetFields();
			this.addClassDialogTableVisible = false;
		},

		// 选择图片
		selFileCallBack(obj) {
			this.addForm.picUrl = obj[0];
			this.editForm.picUrl = obj[0];
		},
		getClass(val) {
			for (let obj of this.pageClassOption) {
				if (obj.value == val) {
					this.addForm.pageClassName = obj.label;
					this.addForm.pageClassId = obj.value;
					/*if (obj.value == 1) {
							this.idTitle = '商品id：'
						} else if (obj.value == 2) {
							this.idTitle = '店铺id：'
						} else if (obj.value == 4) {
							this.idTitle = '促销活动id：'
						} else if (obj.value == 6) {
							this.idTitle = '秒杀活动id：'
						} else if (obj.value == 8) {
							this.idTitle = '拼团活动id：'
						} else if (obj.value == 7) {
							this.idTitle = '聚合页id：'
						}*/
				}
			}
		},
		cancelAddTree() {
			this.$refs.treeForms.resetForm();
			this.$refs.treeForms.clearValidate();
			this.treeDialogTableVisible = false;
		},
		addTree() {
			this.treeDialogTableVisible = true;
			this.addOrUpdateClass = '新增分类';
			this.getTreeList();
			this.loadClass(1);
		},
		editTree(row) {
			row.parentId = row.nodeParentId;
			this.treeForms = row;
			this.treeDialogTableVisible = true;
			this.addOrUpdateClass = '修改分类';
			this.getTreeList();
			this.loadClass(1);
		},

		submitTree(loading, done) {
			this.loadingNewTree = false;
			if (this.treeForms.id) {
				if (!this.treeForms.parentId) {
					delete this.treeForms.parentId;
				}
				delete this.treeForms.$parentId;
				updateClass(this.treeForms).then(res => {
					if (res.data.code == 200) {
						this.$message.success('修改成功!');
						this.getTreeList();
						// location.reload();
					} else {
						this.$message.error(res.data.message);
						this.loadingNewTree = true;
					}
					done();
				});
			} else {
				if (this.treeForms.parentId) {
					this.treeForms.parentId = this.treeForms.parentId;
				} else {
					delete this.treeForms.parentId;
				}
				delete this.treeForms.$parentId;
				addClass(this.treeForms).then(res => {
					if (res.data.code == 200) {
						this.$message.success('操作成功!');
						this.getTreeList();
						// location.reload();
					} else {
						this.$message.error(res.data.message);
						this.loadingNewTree = true;
					}
					done();
				});
			}
			this.cancelAddTree();
		},
		loadClass(index) {
			if(index==1){
				getListsDicData().then(res => {
					this.optionTree.column[1].dicData = res.data.data;
				});
			}else{
				getListsDicData().then(res => {
					this.optionAddTree.column[5].dicData = res.data.data;
				});
			}
			
		}
	}
};
</script>

<style scoped>
.list-tree-box {
	width: 100%;
	height: 450px;
	max-height: 450px;
	display: flex;
	flex-flow: column nowrap;
	justify-content: space-between;
}

.filter-tree {
	flex: 1;
	border: 1px solid #dcdfe6;
	border-radius: 6px;
	overflow-y: scroll;
}

.basic-box {
	width: 100%;
	height: 100% !important;
}

.basic-container .el-card {
	height: 100% !important;
}

.el-card.is-always-shadow,
.el-card__body {
	width: 100%;
	height: 100% !important;
}

.el-container {
	height: 100% !important;
	padding-bottom: 5px;
}

.table-list {
	max-height: 560px;
	min-height: 560px;
}

.el-aside-tree-container {
	width: 210px !important;
	height: 100% !important;
	display: flex;
	flex-flow: column nowrap;
}
.upload {
	display: flex;
	justify-content: flex-start;
	align-items: center;
}
</style>
